package com.mmc.filter;

import cn.hutool.core.util.StrUtil;
import com.mmc.properties.SecurityGatewayProperties;
import com.mmc.utils.JwtUtils;
import com.mmc.utils.ResponseEnum;
import com.mmc.utils.ResponseUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * 作者：李嘉浩
 * 时间：2024-09-16-23:49
 * 功能：
 */

@Configuration
public class MMCGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private SecurityGatewayProperties properties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest.Builder mutate = request.mutate();

        String path = request.getURI().getPath();

        //判断白名单
        if (properties.getWhites().contains(path)){
            return chain.filter(exchange);
        }
        //获取请求头
        String authorization = request.getHeaders().getFirst("Authorization");
        if (StrUtil.isNotBlank(authorization)){
            return ResponseUtil.webFluxResponseWriter(response,"未登录");
        }
        //判断登录token是否正确
        String token = authorization.replace("Bearer ", "");
        Claims claims = JwtUtils.parseToken(token);
        String uuid=claims.get("uuid")+"";
        Boolean aBoolean = stringRedisTemplate.hasKey("access_token" + uuid);
        if (!aBoolean){
            return ResponseUtil.webFluxResponseWriter(response,"未登录");
        }

        //放行
        return chain.filter(exchange.mutate().request(mutate.build()).build());

    }

    @Override
    public int getOrder() {
        return -100;
    }
}
